import { apiClient } from './apiClient'
import { ApiResponse } from '@/types/api'

export interface TableInfo {
  table_name: string
  table_schema: string
  table_type: string
  table_comment?: string
}

export interface ColumnInfo {
  column_name: string
  data_type: string
  is_nullable: boolean
  column_default?: string
  column_comment?: string
  ordinal_position: number
}

export interface SchemaInfo {
  tables: TableInfo[]
  columns: { [tableName: string]: ColumnInfo[] }
  keywords: string[]
  functions: string[]
}

export interface AutoCompleteSuggestions {
  tables: TableInfo[]
  columns: ColumnInfo[]
  keywords: string[]
  functions: string[]
}

export interface AutoCompleteContext {
  currentWord: string
  previousWords: string[]
  position: { line: number, column: number }
}

/**
 * 获取数据库schema信息
 */
export const getSchemaInfo = async (
  connectionId: string,
  refresh = false
): Promise<ApiResponse<SchemaInfo>> => {
  const response = await apiClient.get(
    `/api/schema/connections/${connectionId}/schema`,
    {
      params: { refresh },
    }
  )
  return response.data
}

/**
 * 搜索表名
 */
export const searchTables = async (
  connectionId: string,
  keyword: string
): Promise<ApiResponse<TableInfo[]>> => {
  const response = await apiClient.get(
    `/api/schema/connections/${connectionId}/schema/tables/search`,
    {
      params: { keyword },
    }
  )
  return response.data
}

/**
 * 搜索列名
 */
export const searchColumns = async (
  connectionId: string,
  keyword: string,
  tableName?: string
): Promise<ApiResponse<{table: string, columns: ColumnInfo[]}[]>> => {
  const response = await apiClient.get(
    `/api/schema/connections/${connectionId}/schema/columns/search`,
    {
      params: { keyword, table: tableName },
    }
  )
  return response.data
}

/**
 * 获取表的列信息
 */
export const getTableColumns = async (
  connectionId: string,
  tableName: string
): Promise<ApiResponse<ColumnInfo[]>> => {
  const response = await apiClient.get(
    `/api/schema/connections/${connectionId}/schema/tables/${tableName}/columns`
  )
  return response.data
}

/**
 * 获取自动补全建议
 */
export const getAutoCompleteSuggestions = async (
  connectionId: string,
  context: AutoCompleteContext
): Promise<ApiResponse<AutoCompleteSuggestions>> => {
  const response = await apiClient.post(
    `/api/schema/connections/${connectionId}/schema/autocomplete`,
    context
  )
  return response.data
}

/**
 * 刷新schema缓存
 */
export const refreshSchema = async (
  connectionId: string
): Promise<ApiResponse<SchemaInfo>> => {
  const response = await apiClient.post(
    `/api/schema/connections/${connectionId}/schema/refresh`
  )
  return response.data
}

/**
 * 清除所有schema缓存
 */
export const clearAllSchemaCache = async (): Promise<ApiResponse<void>> => {
  const response = await apiClient.delete('/api/schema/cache')
  return response.data
}